/*
 * ========================================================
 * Copyright(c) 2014 杭州偶尔科技-版权所有
 * ========================================================
 * 本软件由杭州偶尔科技所有, 未经书面许可, 任何单位和个人不得以
 * 任何形式复制代码的部分或全部, 并以任何形式传播。
 * 公司网址
 * 
 * 			http://www.kkkd.com/
 * 
 * ========================================================
 */
package com.simon.mengkou.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.ouertech.android.agm.lib.base.future.core.AgnettyFuture;
import com.ouertech.android.agm.lib.base.future.core.AgnettyResult;
import com.ouertech.android.agm.lib.base.utils.UtilString;
import com.ouertech.android.agm.lib.ui.base.defaults.activity.BaseTopActivity;
import com.simon.mengkou.R;
import com.simon.mengkou.alipay.Alipay;
import com.simon.mengkou.alipay.PayResult;
import com.simon.mengkou.data.bean.base.Address;
import com.simon.mengkou.data.bean.base.Order;
import com.simon.mengkou.data.bean.base.Product;
import com.simon.mengkou.data.bean.base.Shop;
import com.simon.mengkou.data.cache.DataCacheImpl;
import com.simon.mengkou.data.enums.EBuyType;
import com.simon.mengkou.data.enums.EPayResult;
import com.simon.mengkou.data.enums.EPayType;
import com.simon.mengkou.future.base.OuerFutureListener;
import com.simon.mengkou.system.constant.CstOuer;
import com.simon.mengkou.system.global.OuerApplication;
import com.simon.mengkou.system.global.OuerDispatcher;
import com.simon.mengkou.ui.adapter.OrderProductAdapter;
import com.simon.mengkou.ui.dialog.PayDialog;
import com.simon.mengkou.utils.UtilOuer;
import com.simon.mengkou.wxpay.Wxpay;
import com.tencent.mm.sdk.modelbase.BaseResp;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author : Zhenshui.Xia
 * @since : 2016/4/13.
 * desc    : 确认订单界面
 */
public class OrderConfirmActivity extends BaseTopActivity
        implements Alipay.AlipayListener{
    @Bind(R.id.order_detail_id_list)
    ListView mLvList;

    //地址
    TextView mTvAddress;
    //姓名
    TextView mTvName;

    //商品总价
    TextView mTvAmount;
    //折扣
    TextView mTvDiscount;
    //运费
    TextView mTvFreight;
    //总价
    TextView mTvTotal;

    LinearLayout mLlCouponRoot;


    private OrderProductAdapter mAdapter;
    private Shop mShop;
    private Order mOrder;
    private String mCoupon;

    @Override
    protected void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);
        mShop = (Shop) getIntent().getSerializableExtra(CstOuer.KEY.SHOP);
    }

    @Override
    protected void initTop() {
        setTitle(R.string.order_confirm_title);
        setNavigation(R.drawable.common_ic_left_nav);
    }

    @Override
    protected void initLayout() {
        setContentView(R.layout.activity_order_confirm);
    }

    @Override
    protected void initViews() {
        ButterKnife.bind(this);

        //头部
        View header = LayoutInflater.from(this).inflate(R.layout.layout_order_confirm_header, null);
        mTvAddress = (TextView)header.findViewById(R.id.order_detail_id_address);
        mTvName = (TextView)header.findViewById(R.id.order_detail_id_name);
        mLvList.addHeaderView(header);

        header.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OuerDispatcher.presentAddressManagerActivity(OrderConfirmActivity.this);
            }
        });

        //尾部
        View footer = LayoutInflater.from(this).inflate(R.layout.layout_order_detail_footer, null);
        mTvAmount = (TextView)footer.findViewById(R.id.order_detail_id_total_amount);
        mTvFreight = (TextView)footer.findViewById(R.id.order_detail_id_freight);
        mTvDiscount = (TextView)footer.findViewById(R.id.order_detail_id_discount);
        mTvTotal = (TextView)footer.findViewById(R.id.order_detail_id_total);
        mLvList.addFooterView(footer);

        mLlCouponRoot = (LinearLayout)footer.findViewById(R.id.order_detail_id_coupon_root);
        mLlCouponRoot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OuerDispatcher.presentOrderCouponActivity(OrderConfirmActivity.this);
            }
        });

        mAdapter = new OrderProductAdapter(this);
        mLvList.setAdapter(mAdapter);

        setOrder();

        //注册微信支付结果广播
        registerAction(CstOuer.BROADCAST_ACTION.WEIXIN_PAY_ACTION);
        registerAction(CstOuer.BROADCAST_ACTION.ORDER_COUPON_PRESUBMIT_ACTION);
    }


    @Override
    protected void onReceive(Intent intent) {
        super.onReceive(intent);
        //微信支付结果
        if(CstOuer.BROADCAST_ACTION.WEIXIN_PAY_ACTION.equals(intent.getAction())) {
            int code = intent.getIntExtra(CstOuer.KEY.CODE, BaseResp.ErrCode.ERR_SENT_FAILED);
            if(code == BaseResp.ErrCode.ERR_OK) {//支付成功
//                OuerDispatcher.presentPayResultActivity(this, mOrder, null, EPayResult.SUCCESS);
                OuerDispatcher.sendOrderPayBroadcast(this);
                finish();
            } else if(code == BaseResp.ErrCode.ERR_SENT_FAILED) {//微信支付失败
//                OuerDispatcher.presentPayResultActivity(this, mOrder, null, EPayResult.FAILURE);
                finish();
            }
        } else if(CstOuer.BROADCAST_ACTION.ORDER_COUPON_PRESUBMIT_ACTION.equals(intent.getAction())) {
            mCoupon = intent.getStringExtra(CstOuer.KEY.COUPON);
            Order order = (Order) intent.getSerializableExtra(CstOuer.KEY.ORDER);
            OuerApplication.mPreferences.setCouponsPrice(OuerApplication.mUser.getUserId(), String.valueOf(order.getDiscount()));

            mLlCouponRoot.setVisibility(View.GONE);
            //实付总价
            mTvTotal.setText(Html.fromHtml(getString(R.string.my_order_detail_total,
                    UtilOuer.formatPrice(order.getAmount()))));
            //优惠
            mTvDiscount.setText(getString(R.string.common_price,
                    UtilOuer.formatPrice(Float.valueOf(order.getDiscount()))));
        }
    }

    private void setOrder() {
        if(mShop == null) {
            return;
        }

        //设置收货地址
        setAddress();

        //商品总价
        double price = 0;
        for(Product product : mShop.getGoodsList()) {
            price += product.getPrice() * product.getCount();
        }

        mTvAmount.setText(getString(R.string.common_price,
                UtilOuer.formatPrice(price)));
        //运费
        mTvFreight.setText(getString(R.string.common_price,
                UtilOuer.formatPrice(mShop.getFreight())));
        //优惠
        String discount = OuerApplication.mPreferences.getCouponsPrice(OuerApplication.mUser.getUserId());
        if(UtilString.isBlank(discount)) {
            mLlCouponRoot.setVisibility(View.VISIBLE);
            mTvDiscount.setText(getString(R.string.common_price,
                    UtilOuer.formatPrice(0f)));
            //实付总价
            mTvTotal.setText(Html.fromHtml(getString(R.string.my_order_detail_total,
                    UtilOuer.formatPrice(price + mShop.getFreight()))));
        } else {
            mLlCouponRoot.setVisibility(View.GONE);
            mTvDiscount.setText(getString(R.string.common_price,
                    UtilOuer.formatPrice(Float.valueOf(discount))));
            //实付总价
            mTvTotal.setText(Html.fromHtml(getString(R.string.my_order_detail_total,
                    UtilOuer.formatPrice(price + mShop.getFreight() - Float.valueOf(discount)))));
        }

        //商品列表
        mAdapter.setList(mShop.getGoodsList());

        //
    }


    @Override
    protected void onResume() {
        super.onResume();
        setAddress();
    }

    private void setAddress() {
        Address addr = OuerApplication.mCacheFactory.getCache(DataCacheImpl.AddressDefaultCache.class,
                OuerApplication.mUser.getUserId()).getData();
        if(addr != null) {
            //地址
            mTvAddress.setText(getString(R.string.my_order_detail_address,
                    addr.getAddress() + addr.getDetail()));
            //姓名
            mTvName.setText(getString(R.string.my_order_detail_name, addr.getName(),
                    UtilString.nullToEmpty(addr.getPhone())));
        }
    }

    /**
     * 确认
     */
    @OnClick(R.id.order_detail_id_delete)
    public void confirmOrder() {
        //收货地址空
        if(UtilString.isBlank(mTvAddress.getText().toString())) {
            UtilOuer.toast(this, R.string.order_confirm_addr);
            return;
        }

        //确认对话框
        final Address addr = OuerApplication.mCacheFactory.getCache(DataCacheImpl.AddressDefaultCache.class,
                OuerApplication.mUser.getUserId()).getData();
        Product product = mShop.getGoodsList().get(0);
        if(UtilString.isNotBlank(product.getGroupbuyId())) {
            joinGroup(product.getId(), product.getCount(), EBuyType.GROUPBUY, addr.getId());
        } else if(UtilString.isNotBlank(product.getPreSaleId())) {
            joinGroup(product.getId(), product.getCount(), EBuyType.PRESALE, addr.getId());
        } else {
            PayDialog dialog = new PayDialog(this, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int payType = EPayType.ALIPAY;
                    int id = v.getId();
                    if (id == R.id.pay_id_alipay) {//支付宝支付
                        payType = EPayType.ALIPAY;
                    } else if (id == R.id.pay_id_wxpay) {//微信支付
                        payType = EPayType.WEIXIN;
                    }


                    submitOrder(addr.getId(), payType);
                }
            });

            dialog.showAtLocation(mLvList, Gravity.CENTER, 0, 0);
        }
    }

    /**
     * 提交订单
     * @param addressId
     */
    private void submitOrder(String addressId, final int payType) {
        if(mOrder != null) {
            if(payType == EPayType.ALIPAY) {
//                new Alipay(this).pay(mOrder, this);
            } else if(payType == EPayType.WEIXIN) {
//                new Wxpay(this).pay(mOrder);
            }
        } else {
            AgnettyFuture future = OuerApplication.mOuerFuture.submitOrder(addressId, mCoupon,
                    new OuerFutureListener(this) {
                        @Override
                        public void onStart(AgnettyResult result) {
                            super.onStart(result);
                            setWaitingDialog(true);
                        }

                        @Override
                        public void onComplete(AgnettyResult result) {
                            super.onComplete(result);
                            setWaitingDialog(false);
                            mOrder = (Order) result.getAttach();
                            OuerApplication.mPreferences.setCouponsPrice(OuerApplication.mUser.getUserId(), null);

                            if(payType == EPayType.ALIPAY) {
//                                new Alipay(OrderConfirmActivity.this).pay(mOrder, OrderConfirmActivity.this);
                            } else if(payType == EPayType.WEIXIN) {
//                                new Wxpay(OrderConfirmActivity.this).pay(mOrder);
                            }
                        }

                        @Override
                        public void onException(AgnettyResult result) {
                            super.onException(result);
                            setWaitingDialog(false);
                            UtilOuer.toast(OrderConfirmActivity.this, R.string.order_confirm_confirm_failure);
                        }

                        @Override
                        public void onNetUnavaiable(AgnettyResult result) {
                            super.onNetUnavaiable(result);
                            setWaitingDialog(false);
                        }
                    });

            attachDestroyFutures(future);
        }
    }


    private void joinGroup(String id, int quantity, int type, String addressId) {
        AgnettyFuture future = OuerApplication.mOuerFuture.joinGroupBuy(id, quantity, type, addressId,
                new OuerFutureListener(this){
                    @Override
                    public void onStart(AgnettyResult result) {
                        super.onStart(result);
                        setWaitingDialog(true);
                    }

                    @Override
                    public void onComplete(AgnettyResult result) {
                        super.onComplete(result);
                        setWaitingDialog(false);
                        Order order = (Order) result.getAttach();
                        OuerDispatcher.presentOrderDetailActivity(OrderConfirmActivity.this, order.getId(), null);
                        finish();
                    }

                    @Override
                    public void onException(AgnettyResult result) {
                        super.onException(result);
                        setWaitingDialog(false);
                        UtilOuer.toast(OrderConfirmActivity.this, R.string.order_confirm_confirm_failure);
                    }

                    @Override
                    public void onNetUnavaiable(AgnettyResult result) {
                        super.onNetUnavaiable(result);
                        setWaitingDialog(false);
                    }
                });

        attachDestroyFutures(future);
    }

    @Override
    public void onResult(PayResult payResult) {
        String resultStatus = payResult.getResultStatus();

        // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
        if (TextUtils.equals(resultStatus, "9000")) {
//            OuerDispatcher.presentPayResultActivity(this, mOrder, null, EPayResult.SUCCESS);
            OuerDispatcher.sendOrderPayBroadcast(this);
            finish();
        } else {
//            OuerDispatcher.presentPayResultActivity(this, mOrder, null, EPayResult.FAILURE);
            finish();
        }
    }

}
